/*	# 	DS1302代码片段说明
	1. 	本文件夹中提供的驱动代码供参赛选手完成程序设计参考。
	2. 	参赛选手可以自行编写相关代码或以该代码为基础，根据所选单片机类型、运行速度和试题
		中对单片机时钟频率的要求，进行代码调试和修改。
*/								
#include <STC15F2K60S2.H>
#include <intrins.H>

sbit RST=P1^3;
sbit SCK=P1^7;
sbit SDA=P2^3;

unsigned char DS1302_Time[]={23,59,50};

//DS1302发送一个字节
void Write_Ds1302(unsigned  char temp) 
{
	unsigned char i;
	for (i=0;i<8;i++)     	
	{ 
		SCK = 0;
		SDA = temp&0x01;
		temp>>=1; 
		SCK=1;
	}
}   

//DS1302发送地址数据
void Write_Ds1302_Byte( unsigned char address,unsigned char dat )     
{
 	RST=0;	_nop_();
 	SCK=0;	_nop_();
 	RST=1; 	_nop_();  
 	Write_Ds1302(address);	
 	Write_Ds1302(dat);		
 	RST=0; 
}

//DS1302读取地址数据
unsigned char Read_Ds1302_Byte ( unsigned char address )
{
 	unsigned char i,temp=0x00;
 	RST=0;	_nop_();
 	SCK=0;	_nop_();
 	RST=1;	_nop_();
 	Write_Ds1302(address);
 	for (i=0;i<8;i++) 	
 	{		
		SCK=0;
		temp>>=1;	
 		if(SDA)
 		temp|=0x80;	
 		SCK=1;
	} 
 	RST=0;	_nop_();
 	SCK=0;	_nop_();
	SCK=1;	_nop_();
	SDA=0;	_nop_();
	SDA=1;	_nop_();
	return (temp);			
}

void DS1302_SetTime(unsigned char *DS1302_Time)
{
	unsigned char i;
	Write_Ds1302_Byte(0x8e,0);
	for(i=0;i<3;i++)
	{
		DS1302_Time[i]=(DS1302_Time[i]/10<<4)|(DS1302_Time[i]%10);
		Write_Ds1302_Byte(0x84-2*i,DS1302_Time[i]);
	}
	Write_Ds1302_Byte(0x8e,1);
}

void DS1302_SaveTime(unsigned char *DS1302_Time)
{
	unsigned char i;
	for(i=0;i<3;i++)
	{
		DS1302_Time[i]=Read_Ds1302_Byte(0x85-2*i);
		DS1302_Time[i]=(DS1302_Time[i]/16*10)+(DS1302_Time[i]%16);
	}
}


////DS1302上电设置时间
//void DS1302_SetTime()
//{
//	Write_Ds1302_Byte(0x8e,0);	//写保护就用0和1就够了
//	Write_Ds1302_Byte(0x84,DS1302_Time[0]/10*16+DS1302_Time[0]%10);
//	Write_Ds1302_Byte(0x82,DS1302_Time[1]/10*16+DS1302_Time[1]%10);
//	Write_Ds1302_Byte(0x80,DS1302_Time[2]/10*16+DS1302_Time[2]%10);
//	Write_Ds1302_Byte(0x8e,1);
//}

////DS1302存储时间
//void DS13102_SaveTime()
//{
//	unsigned char Temp;
//	Temp=Read_Ds1302_Byte(0x85);
//	DS1302_Time[0]=Temp/16*10+Temp%16;
//	Temp=Read_Ds1302_Byte(0x83);
//	DS1302_Time[1]=Temp/16*10+Temp%16;
//	Temp=Read_Ds1302_Byte(0x81);
//	DS1302_Time[2]=Temp/16*10+Temp%16;
//}

